<template>
  <div class="_wz_staff">
    <Card dis-hover>
      <template #title>搜索</template>
      <Form :model="formDataSearch" label-position="right" :label-width="80" inline>
        <FormItem label="登录账号">
          <i-input v-model="formDataSearch.userName" placeholder="请填写登录账号" clearable />
        </FormItem>
        <FormItem label="用户名">
          <i-input v-model="formDataSearch.name" placeholder="请填写用户名" clearable />
        </FormItem>
        <FormItem label="归属部门">
          <i-input v-model="formDataSearch.inOrgName" placeholder="请填写归属部门" clearable />
        </FormItem>
        <FormItem label="账号状态">
          <i-select v-model.number="formDataSearch.status" filterable placeholder="请选择账号状态" clearable>
            <Option :value="1">正常</Option>
            <Option :value="0">禁用</Option>
          </i-select>
        </FormItem>
        <FormItem label="认证状态">
          <i-select v-model.number="formDataSearch.safetyState" filterable placeholder="请选择账号状态" clearable>
            <Option :value="1">已认证</Option>
            <Option :value="0">未认证</Option>
          </i-select>
        </FormItem>

        <FormItem>
          <Button type="primary" @click="searchSubmit">搜索</Button>
        </FormItem>
      </Form>
    </Card>

    <Card dis-hover style="height: 100%;overflow: hidden;margin: 10px 0 0;">
      <p slot="title">列表</p>
      <template #extra>
        <Button type="primary" @click="addTableData">添加</Button>
      </template>
      <wzTbale ref="wzTbale" :tableData="tableData"></wzTbale>
    </Card>

    <Drawer :title="formTitle" v-model="formOperation" width="720" :draggable="true" :mask-closable="false" :styles="formOperationStyles">
      <staffAdd v-if="formOperation" :selectData="selectData"  @closeFun="closeFun"></staffAdd>
    </Drawer>

    <Modal title="重置密码" v-model="resetType" :footer-hide="true"  :mask-closable="false" width="500" >
      <Form :model="resetData" label-position="right" :label-width="80">
        <div dis-hover :bordered="true" style="height: 150px">
          <FormItem  label="重置密码" v-if="resetType">
            <div>Ab@123456</div>
          </FormItem>
          <div style="color: red">
            *重置为初始密码，登录后会提示修改新密码。
          </div>
        </div>
        <div class="demo-drawer-footer" >
          <Button style="margin-right: 8px" @click="resetType = false">取消</Button>
          <Button type="primary" @click="resetPasswords">提交</Button>
        </div>
      </Form>
    </Modal>

    <Modal title="绑定" v-model="untieType" :footer-hide="true" :mask-closable="false" width="500">
      <Form ref="untieRef" :model="untieData" label-position="right"  :label-width="80" style="height: 100px" :rules="untieTypeRuleVal" >
        <FormItem  label="认证编码" prop="ukeyNo">
          <i-input v-model="untieData.ukeyNo" placeholder="请输入认证编码" clearable />
        </FormItem>
        <div class="demo-drawer-footer" >
          <Button style="margin-right: 8px" @click="untieType = false">取消</Button>
          <Button type="primary" @click="untieSuccess">提交</Button>
        </div>
      </Form>
    </Modal>

  </div>
</template>
<script>


import {
  getCurrentInstance,
  inject,
  nextTick,
  reactive,
  toRefs,
  toRef,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  ref,
  defineComponent,
  toRaw,
  watch,
  resolveComponent
} from 'vue'
import { useRouter,useRoute } from "vue-router";

import { useMainStore } from '../../store'  //pinia 使用 类似 vuex
import { storeToRefs } from 'pinia'//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex
import staffAdd from './staffAdd.vue'
import wzTbale from "../../components/table/index.vue";
//reactive
export default defineComponent({
  name: 'staff',//组件名称
  components: {
    wzTbale,
    staffAdd,
  },//组件引用
  setup (props,context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用
    const $common = inject('$common');//自己封装的方法
    const untieType = ref(false)

    const wzTbale = ref();
    const untieRef = ref();

    const state = reactive({
      tableData: {
        url: apiUrl.systemUserSystemUserPageList,//请求地址
        method: 'post',//请求方式
        where: {},//搜索条件
        height: '100%',//表格高度 auto
        page: true,//分页是否使用
        columns: [//表头数据
          {type: 'index', width: 70, align: 'center', title: '序号'},

          { title: '登录账号', minWidth: 120, key: 'username',tooltip:true,resizable: true},
          { title: '用户名', minWidth: 160, key: 'name',tooltip:true,resizable: true},
          { title: '联系电话', minWidth: 120, key: 'mobile',tooltip:true,resizable: true},
          { title: '电子邮箱', minWidth: 140, key: 'email',tooltip:true,resizable: true},
          { title: '归属部门', minWidth: 140, key: 'inOrgName',tooltip:true,resizable: true},

          { title: "密码强度", minWidth: 140,tooltip:true,resizable: true, key: "strength",render: (h, params) => {
              return h(resolveComponent('Tag'), {type: "dot",color: params.row.strength == 1 ? "success" : "warning"}, params.row.strength == 1 ? "强密码" : "弱密码");
            }
          },
          { title: "认证状态", minWidth: 140,tooltip:true,resizable: true, key: "safetyState",render: (h, params) => {
              return h(resolveComponent('Tag'), {type: "dot",color: params.row.safetyState == 1 ? "success" : "warning"}, params.row.safetyState == 1 ? "已认证" : "未认证");
            }
          },
          { title: '账号状态',  minWidth: 140, key: 'status', render: (h, params) => {
              return h(resolveComponent('Tag'), {type: "dot",color: params.row.status == 1 ? "success" : "error"}, params.row.status == 1 ? "正常" : "禁用");
            }
          },
          { title: "认证编码", minWidth: 200,tooltip:true,resizable: true, key: "safetyUkey" },
          { title: '负责人状态', minWidth: 120, key: 'inOrgState',tooltip:true,resizable: true,
            render: (h, params) => {
              return h('span', {}, !!params.row.inOrgState?'主管':'--')
            }
          },

          { title: '创建时间', minWidth: 180, key: 'createTime',tooltip:true,resizable: true,
            render: (h, params) => {
              return h('span', {}, $common.timeFormatting(params.row.createTime, "yyyy-MM-dd hh:mm:ss"))
            }
          },
          { title: "修改时间", minWidth: 180, key: "updateTime",tooltip:true,resizable: true },
          {title: '登陆时间', minWidth: 180, key: 'loginTime',tooltip:true,resizable: true,},
          {title: '备注', minWidth: 200, key: 'monitorContext',tooltip:true,resizable: true,},
          {title: '操作', fixed: 'right', width: 250,
            render: (h, params) => {
              let operationButtons = [];
              //修改
              operationButtons.push(
                  h('span', {
                    style: {"color": "#2d8cf0", "cursor": "pointer"},
                    onclick: () => {
                      state.formTitle = "修改"
                      state.selectData = JSON.parse(JSON.stringify(params.row));
                      state.formOperation = true;
                    }
                  }, '修改')
              );
              operationButtons.push(h(resolveComponent('Divider'), {type: 'vertical',}, ''))
              //解冻
              operationButtons.push(
                  h("span",
                      {style: { color: "#2d8cf0", cursor: "pointer" },
                        onclick: () => {
                          var data = JSON.parse(JSON.stringify(params.row));
                          thawFun(data);
                        }
                  }, "解冻")
              );
              operationButtons.push(h(resolveComponent('Divider'), {type: 'vertical',}, ''))
              // //认证
              if (params.row.safetyState == 1) {
                operationButtons.push(
                    h('span', {
                      style: {"color": "#2d8cf0", "cursor": "pointer"},
                      onclick: () => {
                        $ViewUIPlus.Modal.confirm({
                          title: '解绑提醒',
                          content: '确定要解绑选中的记录？',
                          onOk: () => {
                              $ViewUIPlus.Spin.show()
                              $axios.post(apiUrl.systemUkeyUnBind, { uuid: params.row.uuid }).then(res => {
                              if (!!res) {
                                $ViewUIPlus.Spin.hide()
                                $ViewUIPlus.Message.success('数据解绑成功');
                                searchSubmit();
                              }
                            }).catch(err => {
                              console.log("失败", err)
                            })
                          },
                          onCancel: () => {
                            //点击取消
                          }
                        })
                      }
                    }, "解绑")
                );
              }else {
                operationButtons.push(
                    h('span', {
                      style: {"color": "#2d8cf0", "cursor": "pointer"},
                      onclick: () => {
                        var data = JSON.parse(JSON.stringify(params.row));
                        state.untieData.systemUserUuid = data.uuid
                        untieType.value = true
                      }
                    }, "绑定")
                );
              }
              operationButtons.push(h(resolveComponent('Divider'), {type: 'vertical',}, ''))
              operationButtons.push(
                  h('span', {
                    style: {"color": "#2d8cf0", "cursor": "pointer"},
                    onclick: () => {
                      state.resetData = JSON.parse(JSON.stringify(params.row));
                      state.resetType = true
                    }
                  }, "重置密码")
              );
              //删除
              operationButtons.push(h(resolveComponent('Divider'), {type: 'vertical',}, ''))
              operationButtons.push(
                  h('span', {
                    style: {"color": "#2d8cf0", "cursor": "pointer"},
                    onclick: () => {
                      $ViewUIPlus.Modal.confirm({
                        title: '删除提醒',
                        content: '确定要删除选中的记录？',
                        onOk: () => {
                          if(params.row.id == 1 || params.row.state == 1){
                            $ViewUIPlus.Message.error('管理员禁止删除');
                            return;
                          }
                          $axios.post(apiUrl.systemUserSystemUserDelete, { uuid: params.row.uuid }).then(res => {
                            if (!!res) {
                              $ViewUIPlus.Message.success('数据删除成功');
                              searchSubmit();
                            }
                          }).catch(err => {
                            console.log("失败", err)
                          })
                        },
                        onCancel: () => {
                          //点击取消
                        }
                      })
                    }
                  }, "删除")
              );

              return h('div', operationButtons);
            }
          },
        ],
        pagingParameters:{// 分页参数
          page:'pageNo',
          limit:'pageSize'
        },
        format: {//返回数据格式
          list: ['data'],//数据list
          count: ['count'],//数据总量
        },
      },


      formDataSearch: {},//搜索表单数据
      formOperation: false,//表单左侧移出
      formOperationStyles: {//表单左侧移出css
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      formTitle: "",//表单名称
      selectData:{},
      resetType:false,//重置密码弹层
      resetData:{},//重置密码的表单
      untieData:{},//认证编码的表单
      //验证
      untieTypeRuleVal:{
        ukeyNo: [{ required: true, message: "请填写认证编码", trigger: "blur" }],
      },
    });

    //解冻
    const thawFun = (data) => {
      $ViewUIPlus.Modal.confirm({
        title: '解冻提醒',
        content: '确定要解冻选中的记录？',
        onOk: () => {
          $ViewUIPlus.Spin.show()
          $axios.post(apiUrl.systemUserResetStatus,{uuid: data.uuid,deptUuid:data.deptUuid }).then((res) => {
            $ViewUIPlus.Spin.hide()
            if (!!res) {
              $ViewUIPlus.Message.success('解冻成功');
              searchSubmit();
            }
          }).catch((err) => {
            console.log("失败", err)
          })
        },
        onCancel: () => {
          //点击取消
        }
      });
    }
    // 绑定
    const untieSuccess = () => {
      untieRef.value.validate(async (valid) => {
        if (valid) {
          $ViewUIPlus.Spin.show();
          $axios.post(apiUrl.systemUkeyBind,state.untieData).then(res => {
            $ViewUIPlus.Spin.hide()
            if (res) {
              untieType.value = false;
              this.$refs.wzTbale.tableLoadData();
              $ViewUIPlus.Message.success('绑定成功');
              state.untieData = {}
            }
          }).catch(err => {
            console.log("失败", err);
          });
        }else {
          $ViewUIPlus.Message.error('请正确填写表单');
        }
      })
    }



    //搜索方法
    const searchSubmit = ()=>{
      let formDataSearch = JSON.parse(JSON.stringify(state.formDataSearch));
      state.tableData.where = formDataSearch;
      wzTbale.value.tableLoadData()
    }

    //添加
    const addTableData = ()=> {
      state.formTitle = "添加"
      state.selectData = { status: 0,inOrgState:0,safetyState:0}
      state.formOperation = true
    }


    //添加修改触发后关闭刷新
    const closeFun = (data)=> {
      if (data) {//添加修改 刷新表单
        searchSubmit();
      }
      state.formOperation = false;
      state.ukeyTion = false;
    }


    //密码提交
    const resetPasswords = ()=>{
      $ViewUIPlus.Modal.confirm({
        title: "重置提醒",
        content: "确定要重置选中的用户密码？",
        onOk: () => {
          $ViewUIPlus.Spin.show()
          $axios.post(apiUrl.systemUserSystemUserResetPass,{ uuid: state.resetData.uuid }).then((res) => {
            $ViewUIPlus.Spin.hide()
            if (!!res) {
              $ViewUIPlus.Message.success('密码重置成功');
              state.resetType = false
              searchSubmit();
            }
          }).catch((err) => {
            console.log("失败", err)
          })
        },
        onCancel: () => {
          //点击取消
        }
      });

    }




    // 其他的生命周期
    onBeforeMount (() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted (() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")

    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate (() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated (() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount (() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted (() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
      searchSubmit,//搜索
      addTableData,//添加
      closeFun,//弹层关闭刷新方法
      resetPasswords,//密码提交
      thawFun,//解冻
      wzTbale,//表格ref
      untieType,
      untieRef,
      untieSuccess,
    }
  }
})


</script>

<style lang="less">
._wz_staff{
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .ivu-card-body {
    height: calc(100% - 51px);
  }
}
</style>

